package com.bana.fvs.protocol;

import com.bana.sys.protocol.Protocol;
import com.bana.sys.utils.Convert;
import io.netty.channel.ChannelHandlerContext;

import java.io.ByteArrayInputStream;
import java.io.DataInputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;


/**
 * 通知协议，用于收取节点通知的工作协议
 * @author Administrator
 *
 */
public class Notice extends Protocol {

	@Override
	public short getId()
	{
		return 0x0006;
	}

	/**
	 * 监听集合
	 */
	private List<NoticeListener> listeners =new ArrayList<>();

	/**
	 * 添加监听
	 * @param listener 监听者
	 */
	public void addListener(NoticeListener listener)
	{
		listeners.add(listener);
	}

    
    @Override 
	protected byte[] responseCore(ChannelHandlerContext context, byte[] requestBuffer, long timeStamp) throws IOException {

		ByteArrayInputStream bais = new ByteArrayInputStream(requestBuffer);
		DataInputStream dis = new DataInputStream(bais);
		int port=Short.toUnsignedInt(dis.readShort());
		short size=dis.readShort();
		byte[] buffer=new byte[size];
		dis.close();
		bais.close();

		System.arraycopy(requestBuffer,4,buffer,0,size);
		for(NoticeListener listener : listeners)
		{
			listener.update(port,buffer);
		}
		return null;
	}

	public interface NoticeListener {

		/**
		 * 通知
		 * @param port 设备端口
		 * @param buffer 数据
		 */
		void update(int port, byte[] buffer);
	}

}
